package com.wwdx.utils;

import java.security.MessageDigest;

/**
 * md5工具类
 * @author liguoliang
 * @date 2018-09-26 10:45:32
 */
public final class Md5Util {

    /**
     * 全局数组
     */
    private final static String[] DIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 返回形式为数字跟字符串
     */
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return DIGITS[iD1] + DIGITS[iD2];
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte bt:b){
            resultSb.append(byteToArrayString(bt));
        }
        return resultSb.toString();
    }

    /**
     * 对字符串进行MD5加密
     */
    public static String encodeByMD5(String original){
        if (original != null){
            try{
                //创建具有指定算法名称的信息摘要
                MessageDigest md = MessageDigest.getInstance("MD5");
                //使用指定的字节数组对摘要进行最后更新，然后完成摘要计算
                byte[] results = md.digest(original.getBytes());
                //将得到的字节数组变成字符串返回
                return byteArrayToHexString(results);
            } catch(Exception ex){
                ex.printStackTrace();
            }
        }
        return null;
    }
}